#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
// #include <bits/types.h>
#include <arpa/inet.h>


int main(void){
    int sockfd = socket(AF_INET,SOCK_STREAM,0);//ipv4,tcp
    if(sockfd == -1){
        perror("sock err");
        return -1;
    }
    //服务器地址:IP 端口号
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port =htons(8888);
    
    addr.sin_addr.s_addr=INADDR_ANY;//本地的ip都可以
    printf("IP=%s\n",inet_ntoa(addr.sin_addr));
    socklen_t addrlen= sizeof(addr);
    //绑定
    if(bind(sockfd,(struct sockaddr*)&addr,addrlen) == -1){
        perror("bind err");
        close(sockfd);
        return -1;
    }

    //监听
    if(listen(sockfd,5) == -1){
        perror("listen err");
        close(sockfd);
        return -1;
    }
    printf("waiting client connect!\n");

    //响应连接
    struct sockaddr_in client_addr;
    socklen_t clientlen;
    int clientfd=accept(sockfd,(struct sockaddr*)&client_addr,&clientlen);
    if(clientfd < 0){
        perror("accept err");
        close(sockfd);
        return -1;
    }
    printf("new connect comming\n");

    struct timeval tv;
    tv.tv_sec = 5; // 设置5秒时间 
    tv.tv_usec = 0; 
    int so_reu =2;
    setsockopt(clientfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &so_reu, sizeof(so_reu));

    //收发数据
    char buf[64]="";
    int ret=0;
    while(1){
        ret =recv(clientfd,buf,sizeof(buf),0);
        if(ret < 0){
            perror("recv err");
            continue;
        }else if(ret > 0){
            printf("recv data:%s\n",buf);
        }else{
            printf("perr quit\n");
            break;
        }
    }

    while(1);
    //关闭
    close(clientfd);
    close(sockfd);


    return 0;
}
